from tensorflow.keras.layers import (Input, Embedding, Conv1D, MaxPooling1D, 
                                   Flatten, Dropout, Dense, Concatenate)
from tensorflow.keras.models import Model

def build_textcnn_model(max_len, embeddings_matrix):
    """构建TextCNN模型
    
    Args:
        max_len: 文本最大长度
        embeddings_matrix: 预训练词向量矩阵
        
    Returns:
        model: 编译好的模型
    """
    main_input = Input(shape=(max_len,), dtype='float64')
    
    # 嵌入层
    embedder = Embedding(
        input_dim=len(embeddings_matrix), 
        output_dim=embeddings_matrix.shape[1],
        weights=[embeddings_matrix],
        trainable=False
    )
    embed = embedder(main_input)
    
    # 卷积层和池化层
    conv_layers = []
    filter_sizes = [3, 4, 5, 10]
    
    for filter_size in filter_sizes:
        conv = Conv1D(256, filter_size, padding='same', 
                     strides=1, activation='relu')(embed)
        pool = MaxPooling1D(pool_size=max_len)(conv)
        conv_layers.append(pool)
        
    # 拼接
    cnn = Concatenate(axis=-1)(conv_layers)
    flat = Flatten()(cnn)
    drop = Dropout(0.2)(flat)
    output = Dense(14, activation='softmax')(drop)
    
    model = Model(inputs=main_input, outputs=output)
    model.compile(loss='categorical_crossentropy', 
                 optimizer='adam',
                 metrics=['accuracy'])
    
    return model 